package cn.tannn.tgateway.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 网关 前置处理demo  mock filter
 * <p> 可以做权限检查等前置处理
 *
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @date 2024/5/30 上午11:41
 */
@Component
@Slf4j
@Order(1)
public class GatewayMockWebFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        log.debug("===>>> spring  [pre] web mock filter ...");

        String isMock = exchange.getRequest().getQueryParams().getFirst("mock");
        if(isMock==null || !Boolean.parseBoolean(isMock)) {
            return chain.filter(exchange);
        }
        //examples 参数存在 mock 就直接返回mock数据
        String mock = """
                {"result": "mock"}
                """;
        return exchange.getResponse()
                .writeWith(Mono.just(exchange.getResponse()
                        .bufferFactory().wrap(mock.getBytes())));
    }
}
